"""
# coding:utf-8
@Time    : 2021/08/30
@Author  : jiangwei
@mail    : qq804022023@gmail.com
@File    : app.py
@Desc    : app
@Software: PyCharm
"""
from flask import Flask, jsonify, request
from utils import check_sign, send_greeting_for_pr, add_label_for_merge, send_greeting_for_issue

app = Flask(__name__)


@app.route('/web-hook/test-handler', methods=['POST'])
def push_handler():
    datas = request.json
    if not check_sign(datas.get('timestamp'), datas.get('sign')):
        return jsonify({'code': 500, 'msg': 'Sign authorization wrong!'})
    return jsonify({'code': 200, 'info': f'{datas.get("hook_name")} Success'})


@app.route('/web-hook/pr-handler', methods=['POST'])
def pull_request_handler():
    datas: dict = request.json
    if not check_sign(datas.get('timestamp'), datas.get('sign')):
        return jsonify({'code': 500, 'msg': 'Sign authorization wrong!'})
    if datas.get('action') == 'open':
        res = send_greeting_for_pr(datas=datas)
        if res.status_code:
            return jsonify({'code': res.status_code, 'msg': 'greeting message send successful.'})

    elif datas.get('action') == 'merge':
        res = add_label_for_merge(datas)
        if res.status_code:
            return jsonify({'code': res.status_code, 'msg': 'greeting message send successful.'})
    else:
        return jsonify({'code': 200, 'msg': 'not supported webhook action'})

    return jsonify({'code': 500, 'msg': 'execute remote server failed.'})


@app.route('/web-hook/issue-handler', methods=['POST'])
def issue_handler():
    datas: dict = request.json
    if not check_sign(datas.get('timestamp'), datas.get('sign')):
        return jsonify({'code': 500, 'msg': 'Sign authorization wrong!'})
    if datas.get('action') == 'open':
        res = send_greeting_for_issue(datas)
        if res.status_code:
            return jsonify({'code': res.status_code, 'msg': 'greeting message send successful.'})
    else:
        return jsonify({'code': 500, 'msg': 'not supported webhook action'})
    return jsonify({'code': 500, 'msg': 'execute remote server failed.'})


if __name__ == '__main__':
    app.run(port=9090, debug=False)
